package logic

import (
	"cloud-disk/core/helper"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/model"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShareBasicSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShareBasicSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShareBasicSaveLogic {
	return &ShareBasicSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShareBasicSaveLogic) ShareBasicSave(req *types.ShareBasicSaveRequest, userIdentity string) (resp *types.ShareBasicSaveResponse, err error) {
	// 获取分享详情
	sb, has, err := l.svcCtx.ShareBasicModel.GetShareBasic(req.ShareBasicIdentity)
	if err != nil {
		resp.Message = "获取分享记录失败 " + err.Error()
		resp.Code = 100
		return resp, nil
	}

	if !has {
		resp.Message = "分享记录不存在"
		resp.Code = 100
		return resp, nil
	}

	// 获取资源详情
	resp = new(types.ShareBasicSaveResponse)
	rep, has, err := l.svcCtx.RepositoryPoolModel.GetRepositoryPoolByIdentity(sb.RepositoryIdentity)
	if err != nil {
		resp.Message = "获取资源详情失败"
		resp.Code = 100
		return resp, nil
	}

	if !has {
		resp.Message = "资源详情不存在"
		resp.Code = 100
		return resp, nil
	}

	ur := model.UserRepostiory{
		Identity:           helper.GetUUID(),
		UserIdentity:       userIdentity,
		ParentId:           int(req.ParentId),
		ReoisitoryIdentity: rep.Identity,
		Ext:                rep.Ext,
		Name:               rep.Name,
	}

	err = l.svcCtx.UserRepostioryModel.CreateUserRepostiory(&ur)
	if err != nil {
		resp.Message = "保存失败"
		resp.Code = 100
		return resp, nil
	}

	resp.Message = "保存成功"
	resp.Code = 200
	resp.Identity = ur.Identity
	return resp, nil
}
